
# Upload File (Store & Upload)
# Rishav Jain

import variables
from profile import profile

import time
import os
import socket

## TESTING
import threading

def makeJSON(Sensor, timestamp):
    sensorID = 1
    channelName = 'channel1'
    sensorName = ''
    unit = ''
    sReadings = ''
        
    if Sensor == variables.TEMP_TAG:
        sensorName = 'TemperatureSensor'
        unit = 'celcius'
        
    elif Sensor == variables.LIGHT_TAG:
        sensorName = 'LightSensor'
        unit = 'none'
        
    elif Sensor == variables.PIR_TAG:
        sensorName = 'PIRSensor'
        unit = 'none'

##    print('Getting Readings - ',timestamp,Sensor)
    fp = open(profile.StorePath + timestamp + '/' + Sensor + '.csv', 'r')
    sReadings = fp.readline()
    fp.close()

    JSON = '{"secretkey":"' + str(profile.APIkey) + '","data":{"loc":"'
    JSON += profile.DeviceLocation + '","dname":"' + profile.DeviceName + '",'
    JSON += '"sname":"' + sensorName + '","sid":' + str(sensorID) + ','
    JSON += '"timestamp":' + str(timestamp) + ',"speriod":' + str(profile.SamplingPeriod) + ','
    JSON += '"channels":[{"cname":"' + channelName + '","unit":"' + str(unit) + '",'
    JSON += '"readings":[' + sReadings + ']}]}}\r\n\r\n'
        
    variables.POST_buffer = 'POST ' + profile.ServerURL + ' HTTP/1.1\r\n'
    variables.POST_buffer += 'Host: ' + profile.ServerIP + '\r\n'
    variables.POST_buffer += 'Accept: */*\r\n'
    variables.POST_buffer += 'Content-Length: ' + str(len(JSON)) + '\r\n'
    variables.POST_buffer += 'Content-Type: application/json; charset=UTF-8\r\n'
    variables.POST_buffer += 'Connection: close\r\n'
    variables.POST_buffer += '\r\n' + JSON
        
    return

def uploadReadings():
    print('UploadTask started')

    while(True):
        if variables.alarmUpload == 1:
            variables.alarmUpload = 0

            print('alarmUpload:1', 'Uploading', time.asctime())

            folders = os.listdir(profile.StorePath)
##            print('uploadReadings', 'No. of Folders', len(folders))

            ERROR = False
            
            for FOLDER in folders:
##                print('uploadReadings', 'Folder - ', FOLDER)

                if ERROR == True:
                    break
                
                files = os.listdir(profile.StorePath + FOLDER)

                for FILE in files:
                    try:
##                        print('uploadReadings', 'File - ', FILE)
                        makeJSON(FILE.strip('.csv'), FOLDER)
                        print(variables.POST_buffer)
                        skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                        skt.connect((profile.ServerIP, profile.ServerPort))
##                        print('Connected to Server')
                        skt.send(variables.POST_buffer)
                        print(skt.recv(1000))
                        skt.close()
                        os.remove(profile.StorePath + FOLDER + '/' + FILE)
                    except:
                        print('\nNetwork Error - ' + time.asctime() + '\n')
                        ERROR = True
                        break

                if len(os.listdir(profile.StorePath + FOLDER)) == 0:
                    print('uploadReadings', 'Removing Folder - ', FOLDER)
                    os.rmdir(profile.StorePath + FOLDER)

## FOR TESTING PURPOSES ONLY
##UploadTask = threading.Thread(target = uploadReadings, args=())
##UploadTask.start()
##
##variables.alarmUpload = 1
